package com.itcms.core.service.impl;

import java.util.Collection;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itcms.common.orm.SearchFilter;
import com.itcms.core.domain.Information;
import com.itcms.core.repository.InformationDao;
import com.itcms.core.service.InformationService;

@Service
@Transactional(readOnly = true)
public class InformationServiceImpl implements InformationService {

	@Autowired
	private InformationDao dao;
	
	public Page<Information> findAll(Integer siteId,
			Map<String, String[]> params, Pageable pageable) {
		return dao.findAll(spec(siteId, params), pageable);
	}
	
	private Specification<Information> spec(final Integer siteId,
			Map<String, String[]> params) {
		Collection<SearchFilter> filters = SearchFilter.parse(params).values();
		final Specification<Information> fsp = SearchFilter.spec(filters,
				Information.class);
		Specification<Information> sp = new Specification<Information>() {
			public Predicate toPredicate(Root<Information> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate pred = fsp.toPredicate(root, query, cb);
				if (siteId != null) {
					pred = cb.and(pred, cb.equal(root.get("site")
							.<Integer> get("id"), siteId));
				}
				return pred;
			}
		};
		return sp;
	}
	
	@Transactional
	public Information save(Information bean) {
		bean = dao.save(bean);
		return bean;
	}

	@Transactional
	public Information get(Integer id) {
	    Information bean = dao.findOne(id);
		return bean;

	}

	@Override
	public Information update(Information bean) {
		bean = dao.save(bean);
		return bean;
	}
}
